package org.example.demo4.fittle;

import java.io.IOException;
import java.io.PrintWriter;


import com.alibaba.fastjson2.JSON;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.demo4.utils.StringUtils;
import org.example.demo4.utils.http.AjaxResult;
import org.example.demo4.utils.login.LoginUser;
import org.example.demo4.utils.login.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;



/**
 * 其他模块拦截器
 */
@Component
public class SupplierAuthenticationTokenFilter extends OncePerRequestFilter
{

    
    @Autowired
    private TokenService tokenService;
    
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        String requestUrl = request.getRequestURI();

        if(!requestUrl.startsWith("/supplier")) {
            chain.doFilter(request, response);
            return;
        }
        if(requestUrl.equals("/supplier/user/verCode") || requestUrl.equals("/supplier/user/login")) {
            chain.doFilter(request, response);
            return;
        }
    	String token = request.getHeader("Authorization");
    	LoginUser user = null;
        if ( StringUtils.isNotBlank(token))
        {
            // 查询用户 TODO
            // user = freightServiceProviderService.getCacheLoginSupplier(token);
        }
        
        if(StringUtils.isBlank(token) ) {
            returnJson(response, JSON.toJSONString(AjaxResult.error(40027, "请填写token")));
        }else if( user == null) {
            returnJson(response, JSON.toJSONString(AjaxResult.error(40027, "登录信息已失效,请重新登录")));
        }else {
        	// 刷新redis有效时间
            // TODO
            // freightServiceProviderService.refreshCacheToken(user);

            chain.doFilter(request, response);
        }
        return;
    }
    
    private void returnJson(HttpServletResponse response, String json) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
//            log.error("response error", e);
        } finally {
            if (writer != null)
                writer.close();
        }
    }

}